package com.xgp.demo01;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 基本的买票例子
 * @author 薛国鹏
 */
public class SaleTicketDemo02 {
    public static void main(String[] args) {
        //多线程操作
        Ticket2 ticket = new Ticket2();

        new Thread(() -> {
                for(int i = 0;i < 50;i++) {
                    ticket.sale();
                }
            },"A").start();
        new Thread(() -> {
            for(int i = 0;i < 50;i++) {
            ticket.sale();
        }},"B").start();
        new Thread(() -> {
            for(int i = 0;i < 50;i++) {
            ticket.sale();
        }},"C").start();
    }
}


/**资源类**/
class Ticket2 {
    private int number = 100;

    Lock lock = new ReentrantLock();

    //买票的方式
    public void sale() {
        lock.lock();
        try {
            if (number > 0) {
                System.out.println(Thread.currentThread().getName() + "卖出了" + number-- + "票，剩余：" + number);
            }
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
}
